/**
 * Copyright (C) 2010, 2011 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.dicodeproject.analysis.restapi;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class HTablePoolHandler {
  
  private HTablePool hTablePool = null;
  private String zookeeperQuorum = "localhost";
  private int zookeeperPort = 2181;
  private Set<String> tableNames = Collections.synchronizedSet(new HashSet<String>(20));
  /** Logger for this class. */
  private static final Logger LOG = LoggerFactory.getLogger(HTablePoolHandler.class);

  @PostConstruct
  public void init() {
    Configuration config = new Configuration();
    config.clear();
    config.set("hbase.zookeeper.quorum", this.zookeeperQuorum);
    config.setInt("hbase.zookeeper.property.clientPort", this.zookeeperPort);
    this.hTablePool = new HTablePool(config, Integer.MAX_VALUE);
  }

  @PreDestroy
  public void destroy() {
    try {
      this.hTablePool.close();
    } catch (IOException e) {
      LOG.error("Error destroying table pool "+e.getMessage());
    }
  }

  @Resource(name="zookeeperQuorum")
  public void setZookeeperQuorum(String zookeeperQuorum) {
    this.zookeeperQuorum = zookeeperQuorum;
  }

  @Resource(name="zookeeperPort")
  public void setZookeeperPort(Integer zookeeperPort) {
    this.zookeeperPort = zookeeperPort;
  }

  public HTableInterface getHTable(String name) {
    this.tableNames.add(name);
    return hTablePool.getTable(name);
  }
}
